<template>
  <el-upload class="img-uploader"
    accept="image/*"
    :action="props.action"
    :headers="headers"
    :show-file-list="false"
    :before-upload="handleBeforeUpload"
    :on-success="handleSuccessUpload"
    :on-progress="handleProgress"
  >
    <el-image class="img" :src="cfg.imageUrl(model)" fit="contain" :style="{width: props.width + 'px', height: props.width + 'px'}" v-if="model !== ''" />
    <el-icon class="img-uploader-icon" :style="{width: props.width + 'px', height: props.width + 'px', lineHeight: props.width + 'px'}" v-else><Plus /></el-icon>
  </el-upload>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProgressEvent, type UploadUserFile } from 'element-plus'
import ResultCode from '@/config/resultcode'
import cfg from '@/config/config'
import { useUserStore } from '@/stores/user'

interface Props{
  action?: string
  headers?: any
  maxSize?: number
  width?: number
}

const model = defineModel<string>({required: true})
const props = withDefaults(defineProps<Props>(), {
  action: cfg.uploadAction,
  headers: {},
  maxSize: 2048,
  width: 178
})
const emit = defineEmits(['uploaded'])
const progress = ref(0)
const headers = computed(() => {
  const store = useUserStore()
  return {
    appkey: cfg.appkey,
    Authorization: cfg.tokenHead + store.userInfo?.token,
    ...props.headers
  }
})

const handleBeforeUpload = (file : any) => {
  const filetype = file.type as string
  const isImg = filetype.substring(0, 6) === 'image/'
  if (!isImg) {
    ElMessage.error('只能上传图片文件')
  }
  const isLimit = file.size / 1024 > props.maxSize
  if (isLimit) {
    ElMessage.error('文件不能大于' + props.maxSize + 'k')
  }

  return !isLimit && isImg
}
const handleSuccessUpload = (res : any, file : UploadUserFile ) => {
  if (res.code === ResultCode.SUCCESS) {
    model.value = res.data.path
    emit('uploaded', [res.data, file])
  }
}
const handleProgress = (evt : UploadProgressEvent, file : UploadUserFile, files : UploadUserFile[] ) => {
  progress.value = evt.percent
}
</script>

<style lang="less">
.img-uploader{
  .el-upload{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    
    &:hover{
      border-color: #409eff;
    }
  }

  .img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }

  .img {
    display: block;
  }
}
</style>